package com.csw.android.player.utils

import android.view.OrientationEventListener
import com.csw.android.dev_utils.utils.ScreenInfo

object ScreenOrientationUtils {
    enum class UIGravity(vararg var orientationRanges: IntRange) {
        /**
         * 正常姿势手握，手机底部为页面底部
         */
        BOTTOM,
        RIGHT,
        TOP,
        LEFT
    }

    init {
        val w = ScreenInfo.WIDTH
        val h = ScreenInfo.HEIGHT
        val angle = (Math.atan(w * 1.0 / h) / Math.PI * 180).toInt()
        val angleRB = angle
        val angleRT = -angleRB + 180
        val angleLT = angleRB + 180
        val angleLB = angleRT + 180
        UIGravity.BOTTOM.orientationRanges = arrayOf(0..angleRB, angleLB..360)
        UIGravity.RIGHT.orientationRanges = arrayOf(angleRB..angleRT)
        UIGravity.TOP.orientationRanges = arrayOf(angleRT..angleLT)
        UIGravity.LEFT.orientationRanges = arrayOf(angleLT..angleLB)
    }

    /**
     * 屏幕方向转UI重力方向
     * @param orientation 屏幕方向 同[OrientationEventListener.onOrientationChanged]的方法参数
     */
    fun orientationToUIGravity(orientation: Int): UIGravity {
        return when {
            orientation in 45..135 -> UIGravity.RIGHT
            orientation in 135..225 -> UIGravity.TOP
            orientation in 225..315 -> UIGravity.LEFT
            else -> UIGravity.BOTTOM
        }
    }

    /**
     * 屏幕方向转UI重力方向,计算会参考屏幕比例
     * @param orientation 屏幕方向 同[OrientationEventListener.onOrientationChanged]的方法参数
     */
    fun orientationToUIGravityByScreenRatio(orientation: Int): UIGravity {
        UIGravity.RIGHT.run {
            orientationRanges.forEach {
                if (it.contains(orientation)) {
                    return this
                }
            }
        }
        UIGravity.TOP.run {
            orientationRanges.forEach {
                if (it.contains(orientation)) {
                    return this
                }
            }
        }
        UIGravity.LEFT.run {
            orientationRanges.forEach {
                if (it.contains(orientation)) {
                    return this
                }
            }
        }
        return UIGravity.BOTTOM
    }


}